<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 -->
<!-- 
* @desc:角色管理新增弹出框组件
* @fileName:role-drawer.vue
* @author:zhouyongjie@yzbdl.ac.cn
* @date:2022-4-6
!-->

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { FormInstance } from "element-plus";
import treeMenu from "@/common/enum/tree-menu";
import { getCurrentInstance } from "vue";
import { showErrorMessage } from "@/common/message";
const { proxy } = getCurrentInstance() as any;
const props = defineProps({
  // 接受表单提交方法
  submitFunc: Function as any,
});
//定义参数
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const checkShow = ref(false);
//判断显隐
const permissionShow = ref(false);
let treeMenuC = JSON.parse(JSON.stringify(treeMenu));
let newtreeMenuC = JSON.parse(JSON.stringify(treeMenu));
//选择框参数
const checkBox = reactive({
  list: [] as any,
});
//所有权限
const permissionList = reactive({
  list: [] as any,
});
//选中的权限
const chooseBox = reactive({
  list: [] as any,
});
//所有选中的权限
let permissionIds = reactive({
  ids: [] as any,
});
const labelPosition = ref("top");
const defaultProps = {
  children: "children",
  label: "text",
};
const ruleForm = reactive({
  roleName: "",
  treedata: treeMenuC,
  newTreeData: newtreeMenuC,
});

/**
 * @description:获取权限菜单
 * @return void
 */
const getPermission = () => {
  const res = proxy.$HTTP.get({
    url: `/permission`,
  });
  res.then((res: any) => {
    if (res.isOk) {
      permissionList.list = res.data;
    }
  });
  res.catch((error: any) => {
    if (error.data instanceof Array) {
      showErrorMessage({
        message: error.data[0].errorMsg,
      });
    } else {
      showErrorMessage({
        message: error.data,
      });
    }
  });
};
//验证规则
const rules = reactive({
  roleName: [
    {
      required: true,
      message: "角色名称不能为空",
      trigger: "blur",
    },
    { min: 1, max: 64, message: "长度为1-64位", trigger: "blur" },
  ],
  treedata: [{ required: true, message: "", trigger: "blur" }],
});

/**
 * @description:提交表单
 * @param {FormInstance | undefined} formEl
 * @return void
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const res = proxy.$HTTP.post({
        url: `/role`,
        data: {
          roleName: ruleForm.roleName,
          permissionIds: permissionIds.ids,
        },
      });
      res.then((res: any) => {
        if (res.isOk) {
          props.submitFunc(valid);
        }
      });
      res.catch((error: any) => {
        if (error.data instanceof Array) {
          showErrorMessage({
            message: error.data[0].errorMsg,
          });
        } else {
          showErrorMessage({
            message: error.data,
          });
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * @description:树节点点击
 * @param {any} node
 * @return void
 */
const nodeClick = (node: any) => {
  checkBox.list = [];
  permissionList.list.forEach((item: any) => {
    if (node.key == item.menuUrl) {
      checkBox.list.push(item);
    }
  });
  permissionShow.value = true;
  if (checkBox.list.length != 0) {
    checkShow.value = true;
  } else {
    checkShow.value = false;
  }
};

/**
 * @description:选择权限
 * @param {any} value
 * @return void
 */
const checkClick = (value: any) => {
  const _ruleForm = JSON.stringify(ruleForm.newTreeData);
  ruleForm.treedata = JSON.parse(_ruleForm);
  permissionIds.ids = value;
  permissionIds.ids.forEach((item: any) => {
    permissionList.list.forEach((ids: any) => {
      if (item === ids.id) {
        ruleForm.treedata.forEach((tree: any) => {
          if (tree.children) {
            tree.children.forEach((tree1: any) => {
              if (tree1.children) {
                tree1.children.forEach((tree2: any) => {
                  if (ids.menuUrl === tree2.key) {
                    tree2.checked = true;
                  }
                });
              } else {
                if (ids.menuUrl === tree1.key) {
                  tree1.checked = true;
                }
              }
            });
          }
        });
      }
    });
  });
};
onMounted(() => {
  getPermission();
});
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    :label-position="labelPosition"
    label-width="120px"
    class="demo-ruleForm"
    :size="formSize"
  >
    <el-form-item prop="roleName" label="角色名称">
      <el-input
        v-model="ruleForm.roleName"
        placeholder="请输入角色名称"
        size="large"
      />
    </el-form-item>
    <el-form-item prop="treedata" label="权限分配">
      <div class="treeContent">
        <div class="title">权限菜单</div>
        <el-tree
          :data="ruleForm.treedata"
          :default-expand-all="true"
          @node-click="nodeClick"
          node-key="id"
          :props="defaultProps"
        >
          <template #default="{ node, data }">
            <span
              class="custom-tree-node"
              :class="{ active: data.checked, '': !data.checked }"
            >
              <span>{{ node.label }}</span>
              <span class="imgSelect" v-show="data.checked === true">
                <img
                  width="17"
                  height="13"
                  src="@/assets/img/host-config/select.png"
                />
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <div class="boxContent" v-show="permissionShow">
        <div class="title">权限展示</div>
        <div v-show="!checkShow">当前菜单下没有权限数据</div>
        <el-checkbox-group
          v-model="chooseBox.list"
          @change="checkClick"
          v-show="checkShow"
        >
          <el-checkbox
            v-for="item in checkBox.list"
            :checked="item.checked"
            :key="item.id"
            :label="item.id"
            >{{ item.permissionName }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
    </el-form-item>
    <el-form-item class="ClickButton">
      <el-button @click="submitForm(ruleFormRef)">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-family: PingFang SC;
  font-weight: 700;
  color: #000000;
  font-size: 14px;
}

:deep(.el-tree-node__content) {
  height: 32px !important;
}
:deep(.el-input) {
  height: 40px;
  background-color: #ffffff;
}
:deep(.el-textarea) {
  height: 100px;
  background-color: #ffffff;
  .el-textarea__inner {
    height: 100px;
  }
}
.treeContent {
  width: 340px;
  float: left;
  .title {
    width: 340px;
    color: rgba(0, 0, 0, 0.5);
    background-color: #f5f5f5;
    font-size: 14px;
    font-weight: 700;
    text-align: center;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .imgSelect {
      margin-right: 120px;
    }
  }
  .active {
    background-color: rgba(245, 245, 245, 1);
    width: 300px;
  }
}
.boxContent {
  width: 340px;
  height: 370px;
  padding-left: 20px;
  float: left;
  .title {
    width: 340px;
    color: rgba(0, 0, 0, 0.5);
    background-color: #f5f5f5;
    font-size: 14px;
    font-weight: 700;
    text-align: center;
  }
}
.ClickButton {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end;
    .el-button {
      width: 68px;
      height: 40px;
      background-color: #ffffff;
      border: 1px solid;
      border-color: #cccccc;
    }
  }
}
</style>
